import {
  Entity,
  PrimaryKey,
  Property,
  ManyToOne,
  Reference,
  wrap,
  Type,
} from "@mikro-orm/core";
import { BaseEntity } from "./Base";
import { User } from "./User";
import { App } from "./App";

function keepJsonValue(val: any) {
  console.log("🚀 ~ keepJsonValue ~ val:", val);
  if (typeof val === "object") {
    return JSON.stringify(val);
  }
  return val;
}

export class JsonType extends Type<string> {
  convertToDatabaseValue(value: string | undefined): string {
    // console.log("🚀 ~ JsonType ~ convertToDatabaseValue ~ value:", value);
    if (!value) {
      return "";
    }

    return Object.prototype.toString.call(value).slice(8, -1) === "Object" ||
      Array.isArray(value)
      ? JSON.stringify(value)
      : value.toString();
  }

  convertToJSValue(value: string): string {
    // console.log("🚀 ~ JsonType ~ convertToJSValue ~ value:", value);
    return value;
  }

  // getColumnType(prop: EntityProperty) {
  //   return `date(${prop.length})`
  // }
}

@Entity()
export class Config extends BaseEntity {
  @Property({ type: "string" })
  name: string;

  @Property({ type: "string", nullable: true })
  introduce: string;

  @Property({ type: "string" })
  type: string; // json text number boolean list object

  // @Property({ type: JsonType })
  @Property({ type: "string" })
  value: string; // app secret for get its configs

  @Property({ type: "string" })
  env: string; // local dev test prod

  // @ManyToOne({ entity: () => App, nullable: true })
  @ManyToOne({ entity: () => App })
  app!: Reference<App>; // response to filed 'app_id'

  @ManyToOne({ entity: () => User })
  creator!: Reference<User>; // response to filed 'creator_id'

  @ManyToOne({ entity: () => User })
  editor!: Reference<User>; // response to filed 'editor_id'

  @Property({ type: "numeric", columnType: "int", default: 0 })
  disabled: number = 0;

  constructor({
    name,
    value,
    type = "text",
    introduce = "",
    env,
    app,
    creator,
    editor,
    disabled = 0,
  }: {
    name: string;
    value: any;
    type: string;
    introduce: string;
    env: string;
    creator: Reference<User>;
    editor: Reference<User>;
    app: Reference<App>;
    disabled: number;
  }) {
    super();
    this.name = name;
    this.value = value;
    this.type = type;
    this.introduce = introduce;
    this.app = app;
    this.creator = creator;
    this.editor = editor;
    this.disabled = disabled;
    this.env = env;
  }
}
